package com.ketai.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ketai.dao.ResearchDao;
import com.ketai.dao.impl.ResearchDaoImpl;
import com.ketai.query.ResearchQuery;
import com.ketai.service.ResearchService;
import com.ketai.util.Pages;
import com.ketai.vo.ResearchVo;

import javax.naming.NamingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author
 * @date 2022-08-10 13:32
 */

public class ResearchServiceImpl  implements ResearchService {
    ResearchDao researchDao = new ResearchDaoImpl();

    @Override
    public Pages<ResearchVo> getAllResearchs(ResearchQuery query) {
        Pages<ResearchVo> result = new Pages<>();
        //封装查询条件 的参数
        List paramsList = new ArrayList();
        StringBuilder sql1 = new StringBuilder("select id,title,img,detail from c_activity ");
        //查询总页数
        StringBuilder sql2 = new StringBuilder("select count(id) as total from c_activity");

        if (StrUtil.isNotBlank(query.getType())) {
            sql1.append(" where tid = ( select id from activity_type where name= ? ) ");
            sql2.append(" where tid = ( select id from activity_type where name= ? ) ");
            paramsList.add(query.getType());
        }

        try {
            long total = researchDao.getTotalResearchCount(sql2.toString(), null);
            result.setDataTotal(total);
            int pageSize = Integer.parseInt(query.getLimit());
            result.setPageNumber(pageSize);
            int pageNo = Integer.parseInt(query.getCurr());
            //计算总页数
            int pages = (int) (total % pageSize == 0 ? total / pageSize : total / pageSize + 1);
            result.setTotalPages(pages);
            //处理当前页码的问题
            pageNo = pageNo > pages ? pages : pageNo;
            pageNo = pageNo <= 0 ? 1 : pageNo;
            result.setCurrentPage(pageNo);
            //执行分页查询
            sql1.append(" order by apply_end_time limit ?, ? ");
            paramsList.add((pageNo - 1) * pageSize);
            paramsList.add(pageSize);
            List<ResearchVo> researchVoList = researchDao.getResearchVoList(sql1.toString(), paramsList.toArray());
            result.setDataItems(researchVoList);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return result;
    }
}
